import 'package:dio/dio.dart';

final translator = GoogleTranslatorRepository();

Future<String> translation(String sourse, String from, String to) {
  return translator.translate(
    source: converCode(from),
    target: converCode(to),
    apiKey: 'AIzaSyBS0lPooqk5eqFGNskuu0quHZAYCYTAPN0',
    text: sourse,
  );
}

String converCode(String code) {
  if (code == 'zh-CN') {
    return code.toLowerCase();
  } else if (code == 'zh-HK') {
    return 'zh-tw';
  } else {
    return code.split('-').first;
  }
}

class GoogleTranslatorRepository {
  final Dio _dio = Dio(BaseOptions(
      baseUrl: 'https://translation.googleapis.com/language/translate/v2'));

  GoogleTranslatorRepository();

  Future<String> translate(
      {String source, String target, String apiKey, String text}) async {
    try {
      var response = await _dio.post(
        '?key=$apiKey',
        data: {'q': text, 'source': source, 'target': target, 'format': 'text'},
      );

      if (response.statusCode == 200 &&
          response.data['data']['translations'] != null &&
          response.data['data']['translations'].length > 0) {
        text = response.data['data']['translations'].first['translatedText'];
      }
    } catch (e) {
      print(e);
    }
    return text;
  }
}
